<?php

namespace Modules\Asset\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Asset\Entities\PackageSku;
use Modules\Asset\Entities\Package;
use Modules\Asset\Entities\Resale;

use Validator;
use ThrowException;
use Auth;
use Setting;
use DB;

// 转售模块
class ResaleController extends Controller
{
    // 转售预览
    public function preview(Request $req)
    {
        $rule = [
            'ids' => ['required', 'array'],  // packageSku的id数组
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $ids = $req->input('ids');

        // 所有要返售的sku
        $packageSkus = PackageSku::belongUser($user)->returnSaleable()->whereIn('id', $ids)->get();

        $skus = [];
        $only = [
            'title',
            'number',
            'thumb',
            'money_price',
            'score_price',
            'total'
        ];

        foreach ($packageSkus as $sku) {
            $skuInfo = $sku->getInfo($only);
            list($returnMoney, $returnRedpack, $returnScore) = $sku->calcReturnSaleInfo();
            $skuInfo['return_money'] = $returnMoney;
            $skuInfo['return_redpack'] = $returnRedpack;
            $skuInfo['return_score'] = $returnScore;

            array_push($skus, $skuInfo);
        }

        list($money, $score) = PackageSku::calcResaleInfoForList($packageSkus);

        $info = [
            'skus' => $skus,
            'advise_money_price' => $money,
            'advise_score_price' => $score,
            'return_sale_ratio' => Setting::returnSaleRatio()
        ];

        return $info;
    }

    // 我的挂售列表
    public function myIndex(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        return [];
    }


    // 转售列表
    public function index(Request $req)
    {
        $options = $req->all();

        $options['scopes']['status'] = 'pending';

        $options['builder'] = Resale::whereHas('package_skus')->where('is_allow_fast_match', 0);

        $options['with'] = ['user', 'package_skus'];

        $options['only'] = [
            'id',
            'uuid',
            'created_at',
            'money_price',
            'score_price',
            'package_skus',
            'union_status',
            'union_status_text',
            'user' => [
                'headimg',
                'name',
            ],
        ];

        $list = Resale::getList($options);

        return $list->generateListResponse();
    }


    // 创建一个转售
    public function store(Request $req)
    {
        $rule = [
            'package_sku_id' => ['int'],
            'package_id' => ['int'],
            'money_price' => ['int'],
            'is_allow_fast_match' => ['required'],
            'score_price' => ['int']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_resale', 1);

        if ($req->input('package_sku_id')) {
            // 转售package sku
            $target = PackageSku::getEntity([
                'id' => $req->package_sku_id,
                'user_id' => $user->id
            ]);

            if ($target->union_status !== 'pending') {
                ThrowException::Conflict('当前物品不可转售~');
            }
        }
        elseif ($req->input('package_id')) {
            // 转售package
            $target = Package::getEntity([
                'id' => $req->package_id,
                'user_id' => $user->id
            ]);
        }

        // 要持的人民币价格
        $moneyPrice = $req->input('money_price');
        // 要挂的积分价格
        $scorePrice = $req->input('score_price');

        DB::beginTransaction();

        // 使用建议转售价
        if ($req->is_allow_fast_match) {
            list($moneyPrice, $scorePrice) = PackageSku::calcResaleInfoForList([$target]);
        }

        // 转售
        $record = $target->createResale($moneyPrice, $scorePrice, [
            'is_allow_fast_match' => $req->is_allow_fast_match
        ]) ?: ThrowException::Conflict('转售失败，请检查物品状态~');

        // 尝试自动购买
        $record->tryAutoBuy();

        DB::commit();

        return [
            'id' => $record->id,
            'uuid'  => $record->uuid,
        ];
    }

    // 转售详情
    public function show(Request $req, $uuid)
    {
        $resale = Resale::getEntity([
            'uuid' => $uuid,
            'with' => ['package_skus', 'user', 'buyer']
        ]);

        $resale->package_skus->each(function ($item) {
            $item->detail_images = @$item->base_sku->detail_images;
        });

        $info = $resale->getInfo([
            'id',
            'uuid',
            'money_price',
            'score_price',
            'created_at',
            'union_status',
            'union_status_text',
            'resale_type',
            'is_public',
            'package_skus' => [
                '*' => [
                    'id',
                    'uuid',
                    'title',
                    'thumb',
                    'money_price',
                    'score_price',
                    'total',
                    'detail_images'
                ]
            ],
            // 'package' => [
            //     'id',
            //     'uuid',
            //     'title',
            //     'thumb',
            //     'sku_total'
            // ],
            'user' => [
                'id',
                'uuid',
                'name',
                'headimg',
                'last_active_at'
            ],
            'buyer' => [
                'id',
                'uuid',
                'name',
                'headimg',
                'last_active_at'
            ]
        ]);

        $info['is_creator'] = 0;

        // 是否转售创建者本人
        if (Auth::user() && Auth::user()->id === $resale->user_id) {
            $info['is_creator'] = 1;
        }

        return [
            'info' => $info
        ];
    }

    // 取消转售
    public function update(Request $req, $uuid)
    {
        $rule = [
            'type' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $resale = Resale::getEntity([
            'uuid' => $uuid,
            'user_id' => $user->id
        ]);

        $type = $req->input('type');

        // 取消转售
        if ($type === 'close') {
            $resale->close() ?: ThrowException::Conflict('转售不在可取消状态~');
        }

        return [];
    }
}
